package com.rlj.messagequeue.common;

import java.io.*;

/**
 * Created with IntelliJ IDEA.
 * Description: 二进制数据的基础工具类
 * User: DELL
 * Date: 2024-02-26
 * Time: 0:56
 */
public class BinaryTool {

    /**
     * object对象 序列化为字节数组
     * 使用内置的 ObjectOutputStream 类进行序列化
     *
     * @param object
     * @return
     * @throws IOException
     */
    public static byte[] toBytes(Object object) throws IOException {
        // ByteArrayOutputStream类 的作用类似于一个变长数组
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
            try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
                objectOutputStream.writeObject(object);
            }
            return byteArrayOutputStream.toByteArray();
        }
    }

    /**
     * 字节数组反序列化为 object对象
     *
     * @param data
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static Object fromBytes(byte[] data) throws IOException, ClassNotFoundException {
        Object object = null;
        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data)) {
            try (ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)) {
                object = objectInputStream.readObject();
            }
        }
        return object;
    }

}
